<template>
  <splitpanes v-if="problem!=null" class="default-theme">
    <pane min-size="20" style="border-bottom: 1px solid #eee;">
      <problem-pane :problem-desc="problem.description">
        <template v-slot:problem-name>{{problem.id}}.{{problem.name}}</template>
        <template v-slot:problem-status>{{problem.status}}</template>
        <template v-slot:problem-difficulty>{{problem.difficulty}}</template>
        <template v-slot:problem-pass>{{problem.pass}} %</template>
        <template v-slot:problem-timeLimit>{{problem.timeLimit}}</template>
        <template v-slot:problem-memoryLimit>{{problem.memoryLimit}}</template>
      </problem-pane>
    </pane>
    <pane min-size="20" style="border-bottom: 1px solid #eee;position: relative">
      <code-edit
      ref="ce"
      :fontsize="'13px'"
      :theme="'eclipse'"
      :mode="languageTable[language]"
      :codefolding="'markbegin'"
      :softwrap="'free'"
      :selectionstyle="'text'"
      :highlightline="true"
      @submit-user-code="submitCode"></code-edit>
      <div class="pane-message" v-show="collapseMsg">
        <p v-html="resultDetails"></p>
      </div>
      <div class="pane-bottom">
        <el-row :gutter="20">
          <el-col :span="4">
            <span class="prompt-message">编程语言：</span>
          </el-col>
          <el-col :span="4">
            <el-select v-model="language" size="small" @change="handleLanguageChange">
              <el-option
                  v-for="item in languageOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" size="small" @click="noticeSubmitCode" :disabled="loading">提交</el-button>
          </el-col>
          <el-col :span="6">
            <span class="prompt-message">{{submitStatus}}</span>
          </el-col>
          <el-col :span="2" :offset="5">
            <el-button class="float-right" :icon="collapseMsg===true?'el-icon-arrow-up':'el-icon-arrow-left'" circle size="mini" @click="collapseMsgPane"></el-button>
          </el-col>
        </el-row>
      </div>
    </pane>
  </splitpanes>
  <div v-else>
    未找到名为{{$route.params.name}}的题目！
  </div>
  <el-dialog
      v-model="dialogVisible"
      width="30%">
    <div>
      <p class="dialog-result" :class="colorClass[colorIndex]">{{ runResult }}</p>
      <span>{{ resultMessage }}</span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false" size="mini">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {Splitpanes, Pane} from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import ProblemPane from "@/components/ProblemPane";
import CodeEdit from "@/components/CodeEdit";
import GLOBAL from "@/assets/js/const"

import {
  getProblem,
  getProblemCode,
  submitCodeToServer,
  getRunResultFromServer
} from "@/network/home";

export default {
  name: "WorkStation",
  components: {
    Splitpanes,
    Pane,
    ProblemPane,
    CodeEdit
  },
  data() {
    return {
      paneSize: 50,
      code: '',
      problem: {},
      dialogVisible: false,
      submitStatus: '',
      runResult: '',
      resultMessage: '',
      resultDetails: '这里显示代码运行结果。',
      loading: false,
      colorClass: ['result-correct', 'result-warning', 'result-wrong'],
      colorIndex: 0,
      collapseMsg: false,
      timer: null,
      statusTable: GLOBAL.statusCode,
      languageOptions: [{value: 0,label: 'C'},{value: 1,label: 'C++'},{value: 2,label: 'Java'}],
      language: 0,
      languageTable:{0: 'c_cpp', 1: 'c_cpp', 2: 'java'}
    }
  },
  created() {
    this.problem.name = this.$route.params.name;
    getProblem(this.problem.name).then(res => {
      // console.log(res);
      if('id' in res.data) { // 包含id字段说明请求到了
        this.problem.status = '-';
        this.problem.id = res.data.id;
        this.problem.difficulty = res.data.difficulty;
        this.problem.pass = res.data.pass;
        this.problem.description = res.data.description;
        this.problem.timeLimit = res.data.timeLimit;
        this.problem.memoryLimit = res.data.memoryLimit;
      } else {
        this.problem = null;
      }
    });
    // 获取初始代码
    // getProblemCode(this.problem.name).then(res => {
    //   this.$refs.ce.setCode(res.data);
    // });
  },
  mounted() {
    window.showLoading = this.showLoading;
    window.hideLoading = this.hideLoading;
    this.$refs.ce.setCode(GLOBAL.cTemplate);
  },
  methods: {
    noticeSubmitCode() {
      this.$refs.ce.emitCode();
    },
    getRunResult(id, count, maxCount) {
      getRunResultFromServer(id).then(res => {
        console.log(res);
        // 查询到的结果不是最终结果的话继续查询
        let result = res.data!=null?parseInt(res.data.result):-1;
        if(result <= 3) { // 继续查询
          if(result !== -1) {
            this.submitStatus = this.statusTable[result];
          }
          // if(this.timer != null) {
          //   clearInterval(this.timer);
          // }
          if(count >= maxCount) {
            this.loading = false;
            this.submitStatus = "查询超时，请重试";
          } else {
            count++;
            setTimeout(()=>{this.getRunResult(id, count, 5)}, 2000);
          }
        } else {
          this.submitStatus = '';
          if(result === 4) { //ac
            this.resultMessage = "用时："+res.data.time+"ms,内存占用："+res.data.memory+"MB";
            this.colorIndex = 0;
          } else if(result === 6) { // wrong answer
            this.collapseMsg = true;
            this.resultDetails = "在运行"+res.data.wrongData+"时实际输出与期望输出不符";
            this.colorIndex = 2;
          } else {
            this.collapseMsg = true;
            this.resultDetails = res.data.errorInfo;
            this.colorIndex = 1;
          }
          this.loading = false;
          this.dialogVisible = true;
          this.runResult = this.statusTable[result];
        }
      });
    },
    submitCode(code) {
      // console.log(code);
      this.loading = true;
      this.submitStatus = "提交中，请稍等";
      submitCodeToServer(this.problem.id, this.language, code).then(res => {
        // console.log(res);
        if(res.data.status === 0) {
          this.submitStatus = "提交成功，等待评测";
          this.resultDetails = "";
          this.resultMessage = "";
          // 获取solutionID并间隔2s查询一次运行结果
          let solutionID = parseInt(res.data.data);
          setTimeout(()=>{this.getRunResult(solutionID, 1, 5)}, 2000);
        } else {
          this.submitStatus = "提交失败，请重试";
          this.loading = false;
        }
      }).catch(error => {
        this.submitStatus = "服务器响应超时，请重试";
        this.loading = false;
      });
    },
    handleLanguageChange(val) {
      console.log(val);
      switch (val) {
        case 0:
          this.$refs.ce.setCode(GLOBAL.cTemplate);
          break;
        case 1:
          this.$refs.ce.setCode(GLOBAL.cppTemplate);
          break;
        case 2:
          this.$refs.ce.setCode(GLOBAL.javaTemplate);
          break;
      }
    },
    showLoading() {
      this.loading = true;
    },
    hideLoading() {
      this.loading = false;
    },
    collapseMsgPane() {
      this.collapseMsg = !this.collapseMsg;
    }
  }
}
</script>

<style scoped>
  .default-theme {
    margin-top: -19px;
    height: 100%;
  }

  .pane-bottom {
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    height: 60px;
    padding: 14px 20px;
    background-color: #fff;
  }

  .dialog-result {
    margin: 0 0 12px 0;
    font-size: 30px;
  }

  .result-correct {
    color: #67c23a;
  }

  .result-warning {
    color: #e6a23c;
  }

  .result-wrong {
    color: #f56c6c;
  }

  .prompt-message {
    vertical-align: center;
    font-size: 14px;
    line-height: 32px;
  }

  .pane-message {
    overflow: scroll;
    font-size: 14px;
    color: #aaa;
    height: 120px;
    background-color: #fff;
    float: left;
    width: 100%;
    position: absolute;
    bottom: 60px;
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    z-index: 4;
    padding: 5px 10px;
  }

  .float-right {
    float: right;
  }
</style>